module.exports = (app) => {
    return async function errorHandle(ctx, next) {
        try {
            await next();
        } catch (err) {
            const { status = 500, message = 'Internal Server Error', detail } = err;
            app.logger.error(JSON.stringify({ status, message, detail }));
            app.logger.error('[-- exception --]:', err);
            app.logger.error('[-- exception --]:', status, message, detail);

            if (message && message.indexOf('template not found') > -1) {
                ctx.status = 302
                ctx.redirect(`${app.options?.homePage} || /`)
                return
            }

            const resBody = {
                success: false,
                code: 50000,
                message: '网络错误，请稍后重试'
            }

            ctx.status = 200
            ctx.body = resBody
        }
    }
}